<template>
  <div id="imageDetailPage">
    <!-- 空间信息 -->
    <a-flex justify="space-between">
      <h2>{{ space.spaceName }}（{{ SPACE_TYPE_MAP[space.spaceType] }}）</h2>
      <a-space size="middle">
        <a-button v-if='canUploadImage' type="primary" :href="`/image/add?spaceId=${id}`" target="_blank">
          + 创建图片
        </a-button>
        <a-button v-if='canManageSpaceUser' type="primary" ghost :icon="h(TeamOutlined)" :href="`/spaceUserManage/${id}`" target="_blank">
          成员管理
        </a-button>
        <a-tooltip :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`">
          <a-progress
            type="circle"
            :percent="((space.totalSize * 100) / space.maxSize).toFixed(1)"
            :size="42"
          />
        </a-tooltip>
        <a-button type="primary" ghost :icon="h(BarChartOutlined)" :href="`/analyze?spaceId=${id}`" target="_blank">
          空间分析
        </a-button>
      </a-space>
    </a-flex>
    <!-- 搜索表单 -->
    <ImageSearchForm :onSearch="onSearch"/>
    <!-- 图片列表 -->
    <ImageList :dataList="dataList" :showOp='true' :onReload='fetchData' :loading="loading" :canEdit='canEditImage' :canDelete='canDeleteImage'/>
    <a-pagination
      style="text-align: right"
      v-model:current="searchParams.current"
      v-model:pageSize="searchParams.pageSize"
      :total="total"
      :show-total="() => `图片总数 ${total} / ${space.maxCount}`"
      @change="onPageChange"
      show-size-changer
      @showSizeChange="onShowSizeChange"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, h, ref, reactive, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import { BarChartOutlined, TeamOutlined } from '@ant-design/icons-vue'
import { formatSize } from '../../utils'
import { getSpaceVoByIdUsingPost } from '@/api/spaceController.ts'
import { listImageVoByPageUsingPost } from '@/api/imageController.ts'
import ImageList from '@/components/ImageList.vue'
import ImageSearchForm from '@/components/ImageSearchForm.vue'
import { SPACE_TYPE_MAP } from '@/constants/space.ts'
import { SPACE_PERMISSION_ENUM } from '@/constants/spaceUser.ts'

const props = defineProps<{
  id: string | number
}>()
const space = ref<API.SpaceVO>({})

// 监听
watch(
  () => props.id,
  (newSpaceId) => {
    fetchSpaceDetail()
    fetchData()
  },
)

// 获取空间详情
const fetchSpaceDetail = async () => {
  try {
    // 获取数据
    const res = await getSpaceVoByIdUsingPost({
      id: props.id as number,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    } else {
      message.error('获取空间详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取空间详情失败：' + e.message)
  }
}

onMounted(() => {
  fetchSpaceDetail()
})

// 数据
const dataList = ref([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = ref<API.ImageQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const onPageChange = (page, pageSize) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  fetchData()
}
const onShowSizeChange = (current: number, pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  fetchData()
};

// 添加搜索条件（将搜索组件中的搜索条件带入）
const onSearch = (params: API.ImageQueryRequest) => {
  searchParams.value = {
    ...searchParams.value,
    ...params,
    current: 1
  }
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = <API.ImageQueryRequest>{
    spaceId: props.id,
    ...searchParams.value,
  }
  const res = await listImageVoByPageUsingPost(params)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadImage = createPermissionChecker(SPACE_PERMISSION_ENUM.IMAGE_UPLOAD)
const canEditImage = createPermissionChecker(SPACE_PERMISSION_ENUM.IMAGE_EDIT)
const canDeleteImage = createPermissionChecker(SPACE_PERMISSION_ENUM.IMAGE_DELETE)
</script>
